<?php


namespace plugins\user\api\controller;


use app\controller\frontend\BaseController;
use app\exception\ModelException;
use app\service\PhoneCodeService;
use plugins\user\model\User;
use plugins\user\validate\UserLoginValidate;
use think\Exception;
use xiaodi\JWTAuth\Facade\Jwt;

class LoginController extends BaseController
{

    /**
     * 注册
     * @throws ModelException
     */
    public function register()
    {
        $param['mobile'] = $this->request->post("mobile/s","");//号码
        $param['code'] = $this->request->post("code/s","");//验证码
        $param['password'] = $this->request->post("password/s","");//密码
        try{
            validate(UserLoginValidate::class)->scene("register")->check($param);
        }catch (\Exception $e){
            throw new ModelException($e->getMessage(),-1);
        }
//        $smsCode = PhoneCodeService::authCode(['phone'=>$param['mobile'],'code'=>$param['code']]);
//        if($smsCode['code']!=0){
//            throw new ModelException($smsCode['msg'],$smsCode['code']);
//        }
        $userModel = new User();
        $info = $userModel->getInfo(['mobile'=>$param['mobile']],"","id")['data'];
        try{
            if(!empty($info)){
                throw new ModelException(lang("用户已注册请去登录"),-1);
            }
           $res = $this->commonRegister($param);
        }catch (\Exception $e){
            throw new ModelException($e->getMessage(),-2);
        }
        return json($res);
    }

    /**
     * 验证码登录
     * @throws ModelException
     */
    public function codeLogin()
    {
        $param['mobile'] = $this->request->post("mobile/s","");//号码
        $param['code'] = $this->request->post("code/s","");//验证码
        try{
            validate(UserLoginValidate::class)->scene("codeLogin")->check($param);
        }catch (\Exception $e){
            throw new ModelException($e->getMessage(),-1);
        }
//        $smsCode = PhoneCodeService::authCode(['phone'=>$param['mobile'],'code'=>$param['code']]);
//        if($smsCode['code']!=0){
//            throw new ModelException($smsCode['msg'],$smsCode['code']);
//        }
        $userModel = new User();
        $info = $userModel->getInfo(['mobile'=>$param['mobile']],"","id,seller_id,mobile as name")['data'];
        if(empty($info)){
            $res = $this->commonRegister($param);
        }else{
            $res = $this->afterLogin([
                'id'=>$info['id'],
                'name'=>$info['name'],
                'seller_id'=>$info['seller_id'],
            ]);
        }
        return json($res);
    }

    /**
     * 密码登录
     * @throws ModelException
     */
    public function pwdLogin()
    {
        $param['mobile'] = $this->request->post("mobile/s","");//号码
        $param['password'] = $this->request->post("password/s","");//密码
        try{
            validate(UserLoginValidate::class)->scene("pwdLogin")->check($param);
        }catch (\Exception $e){
            throw new ModelException($e->getMessage(),-1);
        }
        $userModel = new User();
        $info = $userModel->getInfo(['mobile'=>$param['mobile']],"","id,password,seller_id,mobile as name")['data'];
        if(empty($info)){
            throw new ModelException(lang("请先去注册"),-2);
        }
        if(checkPassword($param['password'],$info['password'])!=true){
            throw new ModelException(lang("密码错误"),-3);
        }
        return json($this->afterLogin($info));
    }

    /**
     * 公共的注册
     * @param $param
     * @return array
     * @throws ModelException
     */
    private function commonRegister($param)
    {
        try{
            unset($param['code']);
            $param['password'] = !empty($param['password'])?makePassword($param['password']):makePassword("123456");
            $param['seller_id'] = $this->sellerId;
            $param['avatar'] = "/system_file/avatar.png";
            $param['nickname'] = $param['mobile'];

            $param['id'] = (new User())->insertGetId($param);
            $param['name'] = $param['mobile'];
            return $this->afterLogin($param);
        }catch (\Exception $e){
            throw new ModelException($e->getMessage(),-4);
        }
    }

    /**
     * 登录注册之后获取token的信息
     * @param $param
     */
    private function afterLogin($param)
    {
        $token  = Jwt::token([
            'uid'=>$param['id'],
            'name' => $param['name'],
            'seller_id' => $param['seller_id']]);
       return dataReturn(0,lang('登录成功'),["token"=>(string)$token]);
    }


}